<template>
  <div class="index">
    <!-- logo  顶部导航展示栏-->
    <div class="app-view">
      <div class="app-view-left">
        <div :style="{width:isCollapse?'64px':180+'px',height:'64px'}" class="logo">
          <el-image
            :style="{width:isCollapse?'64px':180+'px'}"
            :src="isCollapse?require('@/assets/logo1.png'):require('@/assets/logos.png')"
            :fit="'fill'"
          ></el-image>
        </div>
        <el-menu
          class="el-menu-vertical-demo"
          :default-active="defaultActive"
          ref="ul_width"
          :collapse="isCollapse"
          @open="handleOpen"
          @close="handleClose"
          :default-openeds="openedsList"
        >
          <el-submenu v-for="(item,index)  in navList" v-bind:key="index" :index="item.index">
            <template slot="title">
              <i :class="item.icon_class"></i>
              <!-- <img src="../assets/logo.png"  :style="{width:'5px',height:'5px'}" alt=""> -->
              <span slot="title">{{item.title}}</span>
            </template>
            <el-menu-item
              v-for="(items,index)  in item.list"
              v-bind:key="index"
              :default-active="defaultActive1"
              :style="{background:items.edit?'rgba(36, 42, 49, 0.8) !important':'#353441',borderLeft:items.edit?'2px solid #4280f2 !important':'none'}"
              @click.native="toRoute(items.route,{title:item.title,title1:items.title,index:items.index,path:items.route,id_:items.id_})"
            >{{items.title}}</el-menu-item>
          </el-submenu>
        </el-menu>
      </div>

      <div class="r-view">
        <div class="nav-r-top">
          <div class="l-flex">
            <!-- <el-image   :src="require('@/assets/2de5652cb47ab51d7a63fa8541976c6.png')" :fit="'fill'"></el-image> -->
            <svg
              :class=" isCollapse?'show_icons':'show_icon'"
              data-v-61d5e8f5
              t="1492500959545"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="1691"
              xmlns:xlink="http://www.w3.org/1999/xlink"
              width="30"
              height="30"
              @click="switchover"
            >
              <path
                data-v-61d5e8f5
                d="M245.76 173.548V286.72h757.76V173.548H245.76z m0 414.986h757.76V475.34H245.76v113.193z m0 301.814h757.76V777.175H245.76v113.173zM20.48 286.72h102.4V173.548H20.48V286.72z m0 307.2h102.4V480.748H20.48V593.92z m0 286.72h102.4V767.468H20.48V880.64z"
                p-id="10436"
                fill="#ffffff"
              />
              <path
                data-v-61d5e8f5
                d="M245.76 173.548V286.72h757.76V173.548H245.76z m0 414.986h757.76V475.34H245.76v113.193z m0 301.814h757.76V777.175H245.76v113.173zM20.48 286.72h102.4V173.548H20.48V286.72z m0 307.2h102.4V480.748H20.48V593.92z m0 286.72h102.4V767.468H20.48V880.64z"
                p-id="10436"
                fill="#ffffff"
              />
              <path
                data-v-61d5e8f5
                d="M245.76 173.548V286.72h757.76V173.548H245.76z m0 414.986h757.76V475.34H245.76v113.193z m0 301.814h757.76V777.175H245.76v113.173zM20.48 286.72h102.4V173.548H20.48V286.72z m0 307.2h102.4V480.748H20.48V593.92z m0 286.72h102.4V767.468H20.48V880.64z"
                p-id="10436"
                fill="#ffffff"
              />
            </svg>
            <el-breadcrumb v-if="nav_titleList.length>1" separator="/" :style="{width:'auto'}">
              <el-breadcrumb-item
                :style="{color:'#fff'}"
                v-for="(item,index) in nav_titleList"
                v-bind:key="index"
                @click.native="navTop_to(item.path)"
              >{{item.title}}</el-breadcrumb-item>
            </el-breadcrumb>
            <div v-if="nav_titleList.length<=1" :style="{width:'200px'}"></div>
          </div>
          <div class="log_out">
            <div class="login_user_title flex felxR">
              <div>欢迎 {{this.$store.state.user_data.user_real_name}} 登录平台</div>
              <el-dropdown @command="handleCommand" v-if="getTerrace == 1">
                <span class="el-dropdown-link">
                  {{service_list_title||'所属服务商'}}
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    :command="item"
                    v-for="item of service_list"
                    v-bind:key="item.facilitator_id"
                  >{{item.facilitator_name}}</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <el-badge :value="unreadCount" class="flex felxR notification_btn" @click="toRoute('/notification', notification)" v-if="getTerrace == 3" >
              <i class="el-icon-bell notification_icon" @click="toRoute('/notification', notification)"></i>
            </el-badge>
            <div class="log_out_btn" @click="log_out">退出</div>
          </div>
        </div>
        <div
          :infinite-scroll-immediate="false"
          :infinite-scroll-disabled="false"
          style="overflow-x:auto"
          class="nav-Toviews flex flexR center"
        >
          <div class="nav-Toview">
            <div
              v-for="(item,index) in showNavList"
              v-bind:key="index"
              @click="nav_to(showNavList,index,1)"
              :class="item.edit==true?item.class1:item.class"
            >
              {{item.title}}
              <div @click.stop="delete_nav($event,item,index,2)" v-if="index>0">x</div>
            </div>
          </div>
          <!-- 关闭全部 -->
          <div class="close-btn-all flex flexR">
            <div class="btn flex flexC cp" @click="close_all">
              <div class="btn-item flex flexR center">
                <img :src="require('@/assets/closeBtn.png')" alt srcset />
                <div>一键关闭</div>
              </div>
            </div>
          </div>
        </div>
        <indexs v-if="this.$route.path=='/'||this.$route.path==''"></indexs>
        <transition name="component-fade" mode="out-in">
          <keep-alive>
            <router-view v-if="$route.meta.keepAlive"></router-view>
          </keep-alive>
        </transition>
        <!-- <transition name="component-fade" mode="out-in"> -->
          <router-view v-if="!$route.meta.keepAlive"></router-view>
        <!-- </transition> -->
      </div>
    </div>
  </div>
</template>


<script>
import indexs from "./home/indexs";
export default {
  name: "index",
  data() {
    return {
      isCollapse: false, // 伸缩展开
      defaultActive: "1",
      defaultActive1: "1-1", // 子菜单默认激活
      W_with: "", // 展示视图宽度
      isCollapse_width: 0, // logo 宽度
      nav_titleList: [
        {
          title: "首页",
          path: "/"
        }
      ], // 顶部导航
      // navList: this.$nav || [],
      showNavList: [
        // 展示点击导航
        {
          title: "首页",
          path: "/",
          edit: true,
          class: ["nav-Toview-item"],
          class1: ["activeColor", "nav-Toview-item"],
          index: 0
        }
      ],
      notification: {
        title: "消息",
        title1: "消息",
        index: null,
        path: "/notification",
        id_: undefined
      },
      unreadCount: '',  //消息未读数量

      service_list_title: null, // 所属服务商列表-标题
              openedsList: []
    };
},
computed: {
  navList() {
    return this.$store.state.navList;
    },
    getTerrace() {
      return this.$store.state.terrace;
    },
    service_list() {
      return this.$store.state.server_list;
    }
  },
  // 属性监听
  watch: {
    // 监听全局顶部栏变化
    "$store.state.nav_titleList": function(data) {
      this.nav_titleList = data || this.$store.state.nav_titleList || [];
    },
    //  监听全局点击列表变化
    "$store.state.showNavList": function(data) {
      console.log("监听全局变化", data);
      this.showNavList = data || this.$store.state.showNavList || [];
    },
    //  监听左侧菜单栏变化
    "$store.state.navList": function(data) {
      console.log("监听左侧菜单栏变化", data);
    },
    "$store.state.openedsList": function(data) {
      console.log("监听展开栏", data);
    }
  },
  // 页面事件
  methods: {
    handleOpen(key, keyPath) {
      let list    =  this.openedsList;
          list.push(key)
          this.openedsList=list;
    },
    handleClose(key, keyPath) {
        let list = this.openedsList||[];
        list.forEach((v,k)=>{
                 if(v==key){
                      list.splice(k,1)
                 }
        })
        this.openedsList=list;
    },
    // 收缩导航
    switchover() {
      this.isCollapse = !this.isCollapse;
    },
    // 点击显示导航
    nav_to(list, index, type) {
      if (Array.isArray(list) && type == 1) {
        list.forEach((v, k) => {
          v.edit = false;
        });
        list[index].edit = true;
        this.showNavList = list;
        let path = list[index].path || "/",
          query = list[index].query||{},
          data = list[index];
        this.cache_path(data.obj);
        if (this.$route.path === path) {
          return;
        }
        if (path == "/") {
          this.$router.push({ path: path });
          this.changeNav_show(path);
        } else {
          query.types=1;
          this.$router.push({ path: path, query });
          this.changeNav_show(path);
          this.openMen(data);
        }
        this.changeNav_Top(data.obj);
        this.cahngeShowNavList();
      }
    },
    // 作则点击事件  跳转指定路由
    toRoute(path, opt) {
      console.log("path",path)
      console.log('opt',opt)
      if (this.$route.path === path) {
        return;
      }
      this.$router.push({ path: path });
      this.addNav_show(path, opt);
      this.changeNav_show(path);
      this.changeNav_shows(path);
      this.changeNav_Top(opt);
      this.cache_path(opt);
      this.cahngeShowNavList();
    },
    // 追加展示的导航栏
    addNav_show() {
      let list = this.showNavList || [],
        data = arguments,
        newList = [];
      list.forEach((v, k) => {
        if (v.path == data[0]) {
          newList.push(v.path);
        }
      });
      if (newList.length == 0) {
        list.push({
          title: data[1].title1,
          path: data[0],
          edit: true,
          class: ["nav-Toview-item"],
          class1: ["activeColor", "nav-Toview-item"],
          index: data[1].index,
          obj: arguments[1],
          id_: data[1].id_
        });
        this.showNavList = list || [];
        this.defaultActive1 = data[1].index;
      }
    },
    changeNav_show() {
      let list = this.navList || [],
        fn = list => {
          list.forEach((v, k) => {
            if (v.list && Array.isArray(v.list)) {
              fn(v.list);
            } else {
              if (v.route == arguments[0]) {
                v.edit = true;
              } else {
                v.edit = false;
              }
            }
          });
        };
      fn(list);
    },
    changeNav_shows() {
      let list = this.showNavList || [];
      list.forEach((v, k) => {
        if (v.path == arguments[0]) {
          v.edit = true;
        } else {
          v.edit = false;
        }
      });
      this.showNavList = list;
    },
    changeNav_Top(obj) {
      let data = obj || {},
        showTop_ = JSON.stringify(data) == "{}";
      localStorage.setItem(
        "showNavTop",
        JSON.stringify(data || {}) || JSON.stringify({})
      );
      if (data.path == "/" || showTop_ == true) {
        this.nav_titleList = [
          {
            title: "首页",
            path: "/"
          }
        ];
      } else {
        this.nav_titleList = [
          {
            title: "首页",
            path: "/"
          },
          {
            title: data["title"],
            path: data["path"]
          },
          {
            title: data["title1"],
            path: data["path"]
          }
        ];
      }
      this.cache_path(data);
      this.cahngeShowNavList();
    },
    navTop_to(path) {
      if (this.$route.path === path) {
        return;
      } else if (path == "/") {
        this.toHome(path);
        this.$router.push({ path: "/" });
      } else {
        this.$blackRoute({ path: path, query: {}, that: this }); // 返回指定路由-删除标题栏
      }
    },
    // 关闭窗口
    delete_nav(e, item, index, type) {
      e.stopPropagation();
      if (type == 2) {
        let list = this.showNavList || [],
          query = this.showNavList[list.length - 2].query || {};
        list.splice(index, 1);
        this.showNavList = list;
        if (list.length > 0) {
          this.showNavList[list.length - 1].edit = true;
          this.$router.push({
            path: this.showNavList[list.length - 1].path,
            query
          });
          this.changeNav_Top(this.showNavList[list.length - 1].obj);
        } else {
          this.$router.push({ path: "/" });
        }
        this.$changeNavlist(this.showNavList[list.length - 1].path);
        this.cache_path(this.showNavList[list.length - 1].obj);
        this.openMen(this.showNavList[list.length - 1]);
      }
    },
    // 点击首页-
    toHome(path) {
      let showNavList = this.$store.state.showNavList,
        nav_titleList = this.$store.state.nav_titleList;
      nav_titleList = [];
      let url_ = null;
      showNavList.forEach((v, k) => {
        if (v.path == "/") {
          v.edit = true;
          url_ = v.path;
        } else {
          v.edit = false;
        }
      });
      if (url_ == null) {
        showNavList.unshift({
          title: "首页",
          path: "/",
          edit: true,
          class: ["nav-Toview-item"],
          class1: ["activeColor", "nav-Toview-item"],
          index: 0
        });
      }
      this.nav_titleList=[];
      this.cahngeShowNavList();
    },
    // 缓存路由处理
    cache_path() {
      localStorage.setItem(
        "pathObj",
        JSON.stringify(arguments[0]) || JSON.stringify({ path: "/" })
      );
      localStorage.setItem(
        "showNav",
        JSON.stringify(this.showNavList || []) || JSON.stringify([])
      );
    },
    // 如果浏览器刷新 返回到当前路由地址
    return_routePath(obj) {
      if (obj) {
        let opt = JSON.parse(obj) || "";
        let path = opt.path || "/";
        this.changeNav_show(path);
        this.changeNav_shows(path);
        this.showNavList = JSON.parse(localStorage.getItem("showNav")) || [
          {
            title: "首页",
            path: "/",
            edit: true,
            class: ["nav-Toview-item"],
            class1: ["activeColor", "nav-Toview-item"],
            index: 0
          }
        ];
        this.changeNav_Top(
          JSON.parse(localStorage.getItem("showNavTop")) || { path: "/" }
        );
        if (this.$route.path === path) {
          return;
        }
        this.$router.push({ path: path });
      }
    },
    /**
     *
     *   追加字段
     *   深度解析  递归遍历
     *   @param  Array {list}
     */
    superaddition_fields(list) {
      if (list && Array.isArray(list)) {
        let add_ = list => {
          list.forEach((v1, k1) => {
            if (v1.list && Array.isArray(list)) {
              add_(v1.list || []);
            } else {
              v1.id_ = k1 + "-" + 1;
            }
          });
        };
        add_(list || []);
        return list || [];
      } else {
        return [];
      }
    },
    /**
     *
     *   修改全部 导航列表
     *   @param  Array {list}
     */
    changeNavList(list) {
      this.$store.commit("changeState", { navList: list });
    },
    //  顶部点击列表
    cahngeShowNavList() {
      this.$store.commit("changeState", {
        showNavList: this.showNavList || [],
        nav_titleList: this.nav_titleList || []
      });
    },
    // 点击切换所属服务商
    handleCommand(val) {
      //向服务端发送请求，表示切换了所属服务商
      let { code, msg, data } = this.$api.sendSync(
        this.$mapapi.e_swichFacitator,
        { facilitator_id: val.facilitator_id }
      );
      if (code != 200) {
        this.$message.error(msg);
        return;
      }
      this.service_list_title = val.facilitator_name || "所属服务商";
      //再切换本地缓存的 服务商列表，更换默认的服务商
      let serviceList = this.service_list;
      for (let vi of serviceList) {
        vi.is_default = 0; //先全部切换成 0
        if (vi.facilitator_id == val.facilitator_id) vi.is_default = 1; //切换默认服务商
      }
      this.$store.commit("changeState", { service_list: serviceList });
    },
    //  退出登录-将清楚所有缓存数据和全局变量
    log_out() {
      this.$router.replace({ path: "/login" });
    },
    //  打开指定的菜单
    openMen(data) {
      if (data.index == 0 || data.index == undefined) {
        return;
      }
      let index_ = data.index.split("-")[0] || "1";
      let openedsList_ = this.openedsList || [];
      openedsList_.unshift(index_ + "");
      this.openedsList = openedsList_;
    },
    //  关闭所有菜单和显示 回到首页
    close_all() {
      this.openedsList = [];
      this.nav_titleList = [{ title: "首页", path: "/" }];
      this.showNavList = [
        {
          title: "首页",
          path: "/",
          edit: true,
          class: ["nav-Toview-item"],
          class1: ["activeColor", "nav-Toview-item"],
          index: 0
        }
      ];
       this.$router.push({ path: "/" });
       this.$clearNavList();
       localStorage.setItem('pathObj',JSON.stringify({}))
       localStorage.setItem('showNav',JSON.stringify( this.showNavList))
       localStorage.setItem('showNavTop',JSON.stringify({}))
       
    },


    //  服务商首页欢迎页面
    fwelcome(){
      let {code, msg, data} = this.$api.sendSync(this.$mapapi.f_welcome, {});
      if(code != 200)   return  this.$message.error(msg);
      this.unreadCount = parseInt(data.message_count) > 0 ? data.message_count : '' ;

    }

  },
  //  创建后） 完成数据观测，属性和方法的运算，初始化事件，$el属性还没有显示出来
  created() {
    //  console.log("（创建后） 完成数据观测，属性和方法的运算，初始化事件，$el属性还没有显示出来")
    //  this.isCollapse_width=$('.el-menu-vertical-demo').width();
  },
  // 页面响应完
  mounted() {
    /*
    const nav_list = this.superaddition_fields(this.$nav);
    this.changeNavList(nav_list);
    this.navList = nav_list;
    */
    this.return_routePath(JSON.stringify({ path: this.$route.path }));

    //如果是企业端的话，则展示当前默认所属服务商，以及其服务商列表
    if (this.getTerrace == 1) {
      for (let val of this.service_list) {
        if (val.is_default == 1) {
          this.service_list_title = val.facilitator_name;
        }
      }
    }

    //如果是服务商身份，则调取服务商欢迎接口
    if(this.getTerrace == 3)    this.fwelcome();
    

  },
  components: {
    indexs
  }
};
</script>


<style lang="less" :scope="true" src="@/style/index.less">
</style>
